layui.use(["table", "layer", "form","tree"], function() {
	var table = layui.table;
	var $ = layui.jquery;
	var layer = layui.layer;
	var form = layui.form;
	var tree = layui.tree;
	//查询表格数据并渲染
	$("#searchBtn").on("click", function() {
		table.render({
			elem: "#userTable",
			url: "/role/list",
			page: true,
			limit: 5,
			limits: [5, 10, 15, 20],
			where: { username: $("#searchName").val() },
			cols: [[
				{ title: '角色名', field: 'name', width: '50%', align: "center" },
				{ title: '操作', width: '50%', align: "center", toolbar: "#operateTemplate" }
			]]
		});
		//数据表操作事件
		table.on('tool(userTable1)', function(obj) {
			//点击删除按钮事件
			if (obj.event == "del") {
				layer.confirm("你确定要删除该角色吗？", function() {
					$.post("/role/del?id=" + obj.data.id, function() {
						layer.closeAll();
						$("#searchBtn").click();
					});
				}, function() { });
			}
			//点击编辑按钮事件
			if (obj.event == "edit") {
				$.get("/role/" + obj.data.id, function(ret) {
					layer.open({
						type: 1,
						title: "编辑角色",
						content: $("#userFormTemplate").html(),
						area: ['500px', '400px']
					});
					form.val("userForm", ret);
				});
			}
			if(obj.event == "menu"){
				//先弹出窗口
				layer.open({
					type:1,
					title:"绑定菜单",
					area: ['500px', '400px'],
					content:"<div id='menuTree'></div><div><button class='layui-btn' id='saveMenuTree'>保存</button></div>"
				});
				//弹出窗口中的保存绑定菜单按钮事件
				$("#saveMenuTree").on("click",function(){
					var checkedData = tree.getChecked('menuTreeId'); //获取选中节点的数据
					var ids = [];
			      	$.each(checkedData,function(i,v){
						var id = v.id;//一级菜单的ID
						ids.push(id);
						if(v.children){
							$.each(v.children,function(ii,vv){
								var subId = vv.id;
								ids.push(subId);
							});
						}
					});
					$.post("/role/saveMenu",{ids:ids,roleId:obj.data.id},function(){
						layer.msg("绑定成功");
					});
				});
				
				//再用tree组件渲染这个div成树
				$.get("/menus/tree?roleId="+obj.data.id,function(menus){
					tree.render({
						elem:"#menuTree",
						id:"menuTreeId",
						data:menus,
						showCheckbox:true //显示复选框
					});
				});
			}
		});
	}).click();

	//给新增按钮绑定点击事件
	$("#addBtn").on("click", function() {
		layer.open({
			type: 1,
			title: "新增角色",
			content: $("#userFormTemplate").html(),
			area: ['500px', '400px']
		});
		form.render();

	});
	//弹出窗口中保存按钮绑定事件
	$("body").on("click", "#saveBtn", function() {
		$.post("/role/save", form.val("userForm"), function() {
			layer.closeAll();
			$("#searchBtn").click();
		});
	});
	
	
	
});